package com.beney.codec;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class MessagePacketDecoder extends ByteToMessageDecoder {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        in.markReaderIndex();

        // 至少需要 4byte 先获取到数据长度
        if (in.readableBytes() < 4) {
            return;
        }

        int length = in.readInt();
        // TODO: size < 0 使用 assert 还是 抛出异常
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }

        // 长度完整，读取内容
        byte[] msg = new byte[length];
        in.readBytes(msg);
        MessagePacket messagePacket = JSON.parseObject(msg, MessagePacket.class);

        // 添加到 out 中，交给后续的 ChannelHandler 进行处理
        out.add(messagePacket);
        logger.info("[decode][连接 ({}) 解析消息 ({})]", ctx.channel().id(), messagePacket.toString());
    }
}
